<?php

namespace App\Recharge\Api;

use App\Jobs\SynChronousOrder;
use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use App\Recharge\Bean\RequestResultBean;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class Shuyu101 extends AbstractApi
{
    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public function sign(array $array, string $secret_key): string
    {
        ksort($array); //排序post参数
        $signText='';
        foreach ($array AS $k => $val) { //遍历POST参数
            if ($val == '' || $k == 'sign') continue; //跳过这些不签名
            if ($signText) $signText .= '&'; //第一个字符串签名不加& 其他加&连接起来参数
            $signText .= "$k=$val"; //拼接为url参数形式
        }
        return md5($signText . $secret_key);
    }

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $array = [
            'userid'        => $bean->getSupplierNum(), //商户密钥
            'outorderno'    => $bean->getOrderNo(), //订单号
            'goodsid'       => $bean->getGoodsId(), //商品编码
            'buynum'        => $bean->getRechargeNum() * $bean->getStartCharging(),//充值数量,
            'attach'        => json_encode([$bean->getAccount()]),
            'callbackurl'   => $bean->getNotifyUrl(), //异步回调地址
            'maxmoney'      => $bean->getUnitPrice(),
        ];

        $array['sign'] = $this->sign($array, $bean->getSecretKey());

        return $array;
    }

    /**
     * @param InterfaceConfiguration $config
     * @param BasicInformation $dataBean
     * @param RequestResultBean $bean
     * @return RequestResultBean
     */
    public function synchronous_processing(InterfaceConfiguration $config, BasicInformation $dataBean, RequestResultBean $bean): RequestResultBean
    {
        // 第三方接口返回的错误信息
        $errMessage = "";
        // 请求返回信息转数组
        $resp = json2array($bean->getResponse());
        $bean->setFormatResponse($resp);
        // 解析json 解析失败的话 就默认成功
        $result = data_get($resp, 'code') == 1;
        if (!$result) {
            $errMessage = data_get($resp, 'msg', $config->title . '下单失败');
        }
        // 判断并返回
        return $bean->setResult($result)
            ->setErrorMessage($errMessage)
            ->setApiSynchronousEndProcessing(function() use ($result, $resp, $dataBean) {
                if ($dataBean->getGoodsType() == 4){
                    if ($resp['code'] == 1 && !empty($resp['cardlist'])){
                        $data = [
                            'status'=>5,
                            'orderno'=>$dataBean->getOrderNo(),
                            'cami'=>$resp['cardlist']
                        ];
                    }else{
                        $data = [
                            'status' =>4,
                            'orderno'=>$dataBean->getOrderNo(),
                        ];
                    }
                    SynChronousOrder::dispatch($dataBean->getNotifyUrl(),$data)->delay(Carbon::now())->onConnection('redis')->onQueue('sync_order');
                }
            });
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('status', '');
        $order_sn = $request->input('orderno', '');
        $cami = $request->input('cami',false);
        if ($cami){
            if ($status == 5){
                if (empty($cami)){
                    return $this->apiNotifyData($order_sn, $status)
                        ->setExecute(true)
                        ->setRechargeSuccess($status)
                        ->setCami('订单成功但是没有返回卡号');
                }
                $cami = $this->decode_cami($cami);
            }
        }
        return $this->apiNotifyData($order_sn, $status)
            ->setExecute(true)
            ->setRechargeSuccess($status == 5)
            ->setCami($cami);
    }

    /**
     * @param $cami
     * @return string
     */
    public function decode_cami($cami):string
    {
        $cami = explode(' ', $cami[0]);
        $cami_arr = ['sku_one'=>$cami[0], 'sku_two'=>$cami[1] ?? '', 'sku_three'=>'',];
        return json_encode($cami_arr);
    }
}
